package com.atguigu.juc.future;

import java.util.UUID;
import java.util.concurrent.*;

/**
 * @Description: runAsync supplyAsync 测试
 * @author： yeswater
 * @create： 2024/5/28
 */

public class CompletableFutureUseDemo {
	
	public static void main(String[] args) throws ExecutionException, InterruptedException {
		//future1(); 
		future2();
	}
	
	/**
	 * 验证CompletableFuture能完成FutureTask的功能
	 */
	private static void future1() throws InterruptedException, ExecutionException {
		CompletableFuture<UUID> future = CompletableFuture.supplyAsync(() -> {
			System.out.println(Thread.currentThread().getName() + " come in");
			UUID result = UUID.randomUUID();
			try {
				TimeUnit.SECONDS.sleep(5);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			System.out.println("==> 5s后出结果:" + result);
			return result;
		});
		
		System.out.println("==> result: " + future.get()); // 这里 get() 也会阻塞，但是可以用其他 CompletionStage api实现异步
		System.out.println(Thread.currentThread().getName() + " do other jobs");
		
		System.out.println("==> result: " + future.get());
	}
	
	private static void future2() {
		ExecutorService pool = Executors.newFixedThreadPool(3);
		
		try {
			CompletableFuture<UUID> future = CompletableFuture.supplyAsync(() -> {
				System.out.println(Thread.currentThread().getName() + " come in");
				UUID result = UUID.randomUUID();
				try {
					TimeUnit.SECONDS.sleep(5);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
				//int i = 10/0;
				System.out.println("==> 5s后出结果:" + result);
				return result;
			}, pool).whenComplete((v, e) -> {
				System.out.println("==> v: " + v.toString());
				System.out.println("==> e: " + e);
			}).exceptionally(e -> {
				e.printStackTrace();
				System.out.println("==> 出现异常: " + e.getCause() + e.getMessage());
				return null;
			});
			
			System.out.println(Thread.currentThread().getName() + " do other jobs");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.shutdown();
		}
		
	}
	
	
}
